﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using RioLinx.SharePoint.Publishing.Library;
using Microsoft.SharePoint;


namespace SharePoint.Foundation.Publishing.CONTROLTEMPLATES
{
	public partial class UpdatePageTemplate : UserControl
	{
        //Constants for RefreshPageTemplate method
		const string strTemplateLibraryName = "Page Layouts";
		bool bUsePublishing = true;

        //Constants used in Page_Load
        const string constResource = "spfpub";
        const string constBaseContentTypeId = "0x010100f2a9c1c92ef041a086f2feeaa284ff80";
        const string constBasePageLayout = "Basic Page Layout";
        const string constErrorMsg = "(No custom layout page found. Default system layout pages loaded.)";
        const string constLayoutLibraryName = "pageLayoutTitle";
        bool isPageLayout = true;

		protected void Page_Load(object sender, EventArgs e)
		{
            //Case Refresh Page Template (on page)
            if (!Page.IsPostBack && Request.QueryString["ID"] != null && Request.QueryString["List"] != null)
			{
                pnUpdate.Visible = true;
                
                SPWeb curRootWeb = SPContext.Current.Site.RootWeb;
                SPList pageLayoutList = curRootWeb.Lists.TryGetList(Localization.GetValue(constResource, constLayoutLibraryName));

                if (pageLayoutList == null)
                {
                    lstbxPageTemplatePicker.Items.Add(new ListItem(constBasePageLayout));
                    isPageLayout = false;
                    lblMessage.Text = constErrorMsg;
                    return;
                }

                SPListItemCollection itemCollection = pageLayoutList.Items;
                if (curRootWeb.AvailableContentTypes[new SPContentTypeId(constBaseContentTypeId)] != null)
                {
                    SPWeb web = SPContext.Current.Web;
                    string strListGuid = Request.QueryString["List"];
                    string strPageId = Request.QueryString["ID"];
                    try
                    {
                        Guid listGuid = new Guid(strListGuid);
                        int iPageId = Convert.ToInt32(strPageId);
                        SPList list = web.Lists[listGuid];
                        SPListItem itemCurrentPage = list.Items.GetItemById(iPageId);
                        string strCurrentPageLayout = itemCurrentPage["PublishingPageTemplate"] as string;
                        if (strCurrentPageLayout != null)
                        {
                            int counter = 0;
                            foreach (SPListItem item in itemCollection)
                            {
                                SPFieldMultiColumnValue val = (SPFieldMultiColumnValue)item["AssociatedContentType"];
                                lstbxPageTemplatePicker.Items.Add(new ListItem("[" + val[1] + "] " + item.Title, item.File.Url));
                                if (strCurrentPageLayout == item.Name)
                                {
                                    lstbxPageTemplatePicker.SelectedIndex = counter;
                                }
                                counter++;
                            }
                            if (counter == 0)
                            {
                                isPageLayout = false;
                            }
                        }
                        else
                        {
                            foreach (SPListItem item in itemCollection)
                            {
                                SPFieldMultiColumnValue val = (SPFieldMultiColumnValue)item["AssociatedContentType"];
                                lstbxPageTemplatePicker.Items.Add(new ListItem("[" + val[1] + "] " + item.Title, item.File.Url));
                            }
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }

                }
                else
                {
                    isPageLayout = false;
                }

                if (isPageLayout == false)
                {
                    lblMessage.Text = constErrorMsg;
                }
                //lstbxPageTemplatePicker.Items.Add(new ListItem(constBasePageLayout));

			}


            //Case Refresh List Pages Template
            else if (!Page.IsPostBack && Request.QueryString["items"] != null && Request.QueryString["source"] != null) 
            {
                pnListUpdate.Visible = true;

                SPWeb currentWeb = SPContext.Current.Web;
                string source = Request.QueryString["source"];
                string[] items = Request.QueryString["items"].ToString().Split('|');

                try
                {
                    source = source.Substring(1, source.Length - 2).ToLower();
                    Guid sourceID = new Guid(source);
                    SPList sourceList = SPContext.Current.Web.Lists[sourceID];

                    for (int i = 1; i < items.Length; i++)
                    {
                        SPListItem item = sourceList.GetItemById(int.Parse(items[i]));

                        if (item != null)
                        {
                            HtmlGenericControl li = new HtmlGenericControl("li");
                            li.InnerText = item.Url;
                            listSelectedPages.Controls.Add(li);
                        }

                    }
                }
                catch (Exception)
                {
                    throw;
                }

			}
		}

		protected void btnRefresh_Click(object sender, EventArgs e)
		{
			SPSite site = SPContext.Current.Site;
			SPWeb currentWeb = SPContext.Current.Web;

            string strListGuid = Request.QueryString["List"];
			string strItemId = Request.QueryString["ID"];
			try
			{
				Guid listGuid = new Guid(strListGuid);
				int iItemId = Convert.ToInt32(strItemId);
				SPList list = currentWeb.Lists[listGuid];
				SPListItem item = list.Items.GetItemById(iItemId);
				if (item != null)
				{
                    string strSourceFilePath = lstbxPageTemplatePicker.SelectedValue;
					FileManager.RefreshPageFromLayout(item, strSourceFilePath, bUsePublishing);
				}
                pnUpdate.Visible = false;
                pnResult.Visible = true;
                lblResult.Text = "Page template update was successful";
                lblResult.Style.Add("color", "#059ce8");
			}
			catch (Exception ex)
			{
                pnUpdate.Visible = false;
                pnResult.Visible = true;
                lblResult.Text = "Page template update failed: " + ex.ToString();
                lblResult.Style.Add("color", "#dd4749");
				throw;
			}

		}

        protected void btnRefreshList_Click(object sender, EventArgs e)
        {
            SPWeb currentWeb = SPContext.Current.Web;

            string source = Request.QueryString["source"];
            string[] items = Request.QueryString["items"].ToString().Split('|');

            try
            {
                source = source.Substring(1, source.Length - 2).ToLower();
                Guid sourceID = new Guid(source);
                SPList sourceList = SPContext.Current.Web.Lists[sourceID];

                for (int i = 1; i < items.Length; i++)
                {
                    SPListItem item = sourceList.GetItemById(int.Parse(items[i]));

                    if (item != null)
                    {
                        FileManager.RefreshListPageFromLayout(item, strTemplateLibraryName, bUsePublishing);
                    }
                }
                pnListUpdate.Visible = true;
                pnResult.Visible = true;
                lblResult.Text = "Updating list pages template succeed";
                lblResult.Style.Add("color", "#059ce8");
            }
            catch (Exception)
            {
                pnListUpdate.Visible = true;
                pnResult.Visible = true;
                lblResult.Text = "Updating list pages template failed";
                lblResult.Style.Add("color", "#dd4749");
                throw;
            }

        }
    }
}
